<?php

class WidgetController extends AdminController {

    const MODEL_CLASS_NAME = 'Widget';

    //public $First="121211";
    public function init() {
	parent::init();
	$this->mediaConfig = 'image';
    }

    /**
     * 
     * @param type $updateID
     * @param type $type If it will insert image to text field, type is null. Or if it will insert to editor, 
     * type is 'editor'
     */
    public function actionBrowse($updateID, $type) {
	if ($type == 'editor') {
	    
	}
	if (Yii::app()->request->isAjaxRequest) {
	    $this->renderPartial('_file_browser', array('updateID' => $updateID, 'type' => $type), false, true);
	}
    }

    public function actionIndex() {

	$model = new Widget(Category::SCENARIO_SEARCH);
	$model->unsetAttributes();  // clear any default values

	if (isset($_GET[self::MODEL_CLASS_NAME])) {
	    $model->attributes = $_GET[self::MODEL_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_GET[self::MODEL_CLASS_NAME]);
	} else if (isset($_POST[self::MODEL_CLASS_NAME])) {
	    $model->attributes = $_POST[self::MODEL_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_POST[self::MODEL_CLASS_NAME]);
	} else {
	    $modelState = Yii::app()->user->getState(app()->controller->id . self::MODEL_CLASS_NAME);
	    if ($modelState != null)
		$model->attributes = $modelState;
	}

	$this->render('index', array('model' => $model,));
    }

    public function actionRefresh() {
	//Remove session
	Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, null);

	$this->redirect(url(app()->controller->id));
    }

    function actions() {
	return array(
	    'updatebanner' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'view' => 'updateBanner',
		'customAction' => 'updateBanner',
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_WIDGET', 'widget'))))
	    ),
	    'updatetab' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'view' => 'updateTab',
		'customAction' => 'updateTab',
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_WIDGET', 'widget'))))
	    ),
	    'updatecustomhtml' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'view' => 'updateCustomHtml',
		'customAction' => 'updateCustomHtml',
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_WIDGET', 'widget'))))
	    ),
	    'active' => array(
		'class' => 'lib.components.actions.LGActiveItemAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'itemName' => t('LBL_WIDGET', 'widget'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_WIDGET', 'widget'))))
	    ),
	);
    }

    public function loadModel() {
	$model = null;
	if (isset($_GET['id'])) {
	    $ids = explode(',', $_GET['id']);
	    if (isset($ids)) {
		$criteria = new CDbCriteria;
		$criteria->addInCondition('id', $ids);
		$model = Widget::model()->findAll($criteria);
	    }
	}
	return $model;
    }

    public function createDisplayNameInNameColum($widgetModel) {
	$action = '';
	$widgetType = $widgetModel->widget_type;

	switch ($widgetType) {
	    case LGConstantWidgetType::BANNER:
		$action = 'updatebanner';
		break;
	    case LGConstantWidgetType::TAB:
		$action = 'updatetab';
		break;
	    case LGConstantWidgetType::CUSTOM_HTML:
		$action = 'updatecustomhtml';
		break;
	    default:
		throw new CHttpException(500, t('500', 'messages'));
		break;
	}

	return CHtml::link(CHtml::encode($widgetModel->name), url('widget/' . $action, array("id" => $widgetModel->id)));
    }

    public function createEditIconInActionColum($widgetModel) {
	$widgetType = $widgetModel->widget_type;

	$action = '';

	switch ($widgetType) {
	    case LGConstantWidgetType::BANNER:
		$action = 'updatebanner';
		break;
	    case LGConstantWidgetType::TAB:
		$action = 'updatetab';
		break;
	    case LGConstantWidgetType::CUSTOM_HTML:
		$action = 'updatecustomhtml';
		break;
	    default:
		throw new CHttpException(500, t('500', 'messages'));
		break;
	}

	return CHtml::link('', url("widget/" . $action, array("id" => $widgetModel->id)), array('class' => 'icon edit'));
    }

    public function updateBanner($model, $action) {
	//Check SlideItem Data 
	$slideItems = isset($_POST['SlideItem']) ? $_POST['SlideItem'] : NULL;
	$widgetData = isset($_POST[self::MODEL_CLASS_NAME]) ? $_POST[self::MODEL_CLASS_NAME] : NULL;

	$msg = NULL;
	if ($widgetData != NULL && $slideItems != NULL && is_array($slideItems)) {

	    $widget = $model;
	    $widget->attributes = $widgetData;
	    if ($widget == NULL || count($widget) == 0) {
		throw new CHttpException(404, t('404', 'messages'));
	    }

	    $widget->validate();

	    $length = count($slideItems);
	    $slideItemModels = array();


	    //set Post data to $models
	    for ($i = 0; $i < $length; $i++) {
		$s = new SlideItem;
		$s->attributes = $slideItems[$i];
		array_push($slideItemModels, $s);
	    }

	    $model->customObject = $slideItemModels;

	    //Validate Slide Item
	    $isValid = true;
	    foreach ($slideItemModels as $m) {

		if (!$m->validate()) {
		    $isValid = false;
		}
	    }

	    //If it's valid data, encode to json and save widget
	    //Else add error to Slide Item
	    if ($isValid) {
		$json = json_encode($slideItems);

		// Set json string to params
		$widget->params = $json;

		$isUpdated = $widget->save();

		if ($isUpdated) {
		    $msg = new LGMessage(MsgType::SUCCESS, $action->messages['success']);
		} else {
		    $this->render($action->view, array(
			'model' => $model));
		    app()->end();
		}
	    } else {
		$this->render($action->view, array(
		    'model' => $model));
		app()->end();
		//$msg = new LGMessage(MsgType::ERROR, $action->messages['error']);
	    }
	}

	return $msg;
    }

    public function updateTab($model, $action) {
	//Check SlideItem Data 
	$tabItems = isset($_POST['TabItem']) ? $_POST['TabItem'] : NULL;
	$widgetData = isset($_POST[self::MODEL_CLASS_NAME]) ? $_POST[self::MODEL_CLASS_NAME] : NULL;

	$msg = NULL;
	if ($widgetData != NULL && $tabItems != NULL && is_array($tabItems)) {

	    /* @var $model Widget */
	    $widget = $model;
	    $widget->attributes = $widgetData;

	    $widget->validate();

	    if ($widget == NULL || count($widget) == 0) {
		throw new CHttpException(404, t('404', 'messages'));
	    }

	    $length = count($tabItems);
	    $slideItemModels = array();


	    //set Post data to $models
	    for ($i = 0; $i < $length; $i++) {
		$s = new TabItem;
		$s->attributes = $tabItems[$i];

		//Remove <script> tag
		$s->description =
			strip_tags_content($s->description, '<script>', true);
		array_push($slideItemModels, $s);
	    }

	    $model->customObject = $slideItemModels;

	    //Validate Slide Item
	    $isValid = true;
	    foreach ($slideItemModels as $m) {

		if (!$m->validate()) {
		    $isValid = false;
		}
	    }

	    //If it's valid data, encode to json and save widget
	    //Else add error to Slide Item
	    if ($isValid) {
		$json = json_encode($tabItems);
		// Set json string to params
		$widget->params = $json;

		$isUpdated = $widget->save();

		if ($isUpdated) {
		    $msg = new LGMessage(MsgType::SUCCESS, $action->messages['success']);
		} else {
		    $this->render($action->view, array(
			'model' => $model));
		    app()->end();
		}
	    } else {
		$this->render($action->view, array(
		    'model' => $model));
		app()->end();
	    }
	}

	return $msg;
    }

    public function updateCustomHtml($model, $action) {
	//Check SlideItem Data 
	$customHtml = isset($_POST['CustomHTML']) ? $_POST['CustomHTML'] : NULL;
	$widgetData = isset($_POST[self::MODEL_CLASS_NAME]) ? $_POST[self::MODEL_CLASS_NAME] : NULL;

	$msg = NULL;
	if ($widgetData != NULL && $customHtml != NULL && is_array($customHtml)) {

	    $widget = $model;
	    $widget->attributes = $widgetData;

	    if ($widget == NULL || count($widget) == 0) {
		throw new CHttpException(404, t('404', 'messages'));
	    }
	    $widget->validate();

	    $model->customObject = new CustomHTML;
	    $model->customObject->attributes = $customHtml;

	    //Remove <script> tag
	    $model->customObject->content =
		    strip_tags_content($model->customObject->content, '<script>', true);
	    $isValid = $model->customObject->validate();


	    //If it's valid data, encode to json and save widget
	    //Else add error to Slide Item
	    if ($isValid) {
		$json = json_encode($customHtml);

		// Set json string to params
		$widget->params = $json;

		$isUpdated = $widget->save();

		if ($isUpdated) {
		    $msg = new LGMessage(MsgType::SUCCESS, $action->messages['success']);
		} else {
		    $this->render($action->view, array(
			'model' => $model));
		    app()->end();
		}
	    } else {
		$this->render($action->view, array(
		    'model' => $model));
		app()->end();
	    }
	}

	return $msg;
    }

}
